﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading.Tasks;
using System.ServiceModel.Syndication;
using System.Xml;

namespace TrendingTopics
{
    public partial class TrendingTopic : UserControl
    {

        //PILIHAN ISIAN PROPERTY KATEGORI
        public enum Kategori
        {
            Nasional,
            Ekonomi,
            Olahraga,
            Teknologi,
        }

        //PILIHAN ISIAN PROPERTY JUMLAH TOPICS
        public enum JumlahTopics
        {
            _5,
            _10,
        }

        //FIELD-FIELD
        private Kategori _kategori;
        private JumlahTopics _jumlahTopics;
        private Color _backColorOdd = Color.Gray;
        private Color _backColorEven = Color.White;
        private Color _foreColorTopics = Color.Black;

        //ASSESOR DAN MUTATOR PROPERTY KATEGORI
        public Kategori kategori
        {
            set {
                this._kategori = value;
                label3.Text = value.ToString().ToUpper();
            }

            get {

                return _kategori;
            }
        }

        //ASSESOR DAN MUTATOR JUMLAH TOPICS
        public JumlahTopics jumlahTopics
        {
            set {
                this._jumlahTopics = value;
                viewList();
            }

            get {
                return _jumlahTopics;
            }
        }

        //ASSESOR DAN MUTATOR PROPERTY BACKCOLOR UNTUK ITEM TOPIC GANJIL
        public Color backColorOdd
        {
            set {
                this._backColorOdd = value;
                viewList();
            }

            get {
                return _backColorOdd;
            }
        }

        //ASSESOR DAN MUTATOR PROPERTY BACKCOLOR UNTUK ITEM TOPIC GENAP
        public Color backColorEven
        {
            set
            {
                this._backColorEven = value;
                viewList();
            }

            get
            {
                return _backColorEven;
            }
        }

        //ASSESOR DAN MUTATOR PROPERTY FORECOLOR UNTUK ITEM-ITEM TOPICS
        public Color foreColorTopics 
        {
            set
            {
                this._foreColorTopics = value;
                viewList();
            }

            get
            {
                return _foreColorTopics;
            }
        }

        //ASSESOR DAN MUTATOR PROPERTY FORECOLOR UNTUK HEADER1 YAITU TULISAN “TRENDING”
        public Color foreColorHeader1
        {
            set
            {
                label1.ForeColor = value;
            }

            get
            {
                return label1.ForeColor;
            }
        }

        //ASSESOR DAN MUTATOR PROPERTY FORECOLOR UNTUK HEADER2 YAITU TULISAN “TOPICS”
        public Color foreColorHeader2
        {
            set
            {
                label2.ForeColor = value;
            }

            get
            {
                return label2.ForeColor;
            }
        }

        //ASSESOR DAN MUTATOR PROPERTY FORECOLOR UNTUK CATEGORY
        public Color foreColorCategory
        {
            set
            {
                label3.ForeColor = value;
            }

            get
            {
                return label3.ForeColor;
            }
        }

        XmlReader readerDetik;
        XmlReader readerKompas;
        XmlReader readerAntara;
        XmlReader readerViva;

        SyndicationFeed feedDetik = new SyndicationFeed();
        SyndicationFeed feedKompas = new SyndicationFeed();
        SyndicationFeed feedAntara = new SyndicationFeed();
        SyndicationFeed feedViva = new SyndicationFeed();


        

        string keyword;
        

        public TrendingTopic()
        {
            InitializeComponent();

            label1.ForeColor = Color.Gray;
            label2.ForeColor = Color.FromArgb(224,224,224);
            label3.ForeColor = Color.White;

            viewList();
            
        }

        private void viewList()
        {
            int x = 5;

            if (jumlahTopics == JumlahTopics._5) x = 5;
            else if (jumlahTopics == JumlahTopics._10) x = 10;

            listBox1.Items.Clear();
            for (int i = 1; i <= x; i++)
            {
                listBox1.Items.Add("Topik " + i);
            }
        }


        //MENGAMBIL DATA DARI RSS
        private void createReader() {

            readerDetik = readerKompas = readerAntara = readerViva = null;
           
            string dt="", an="", vi="";

            if (kategori == Kategori.Nasional)
            {
                dt = "589693";
                an = "nasional";
                vi = "nasional";
               
                readerKompas = XmlReader.Create("http://www.kompas.com/getrss/nasional"); 
                feedKompas = SyndicationFeed.Load(readerKompas);
                
            }
            else if (kategori == Kategori.Ekonomi)
            {
                dt = "590259";
                an = "ekonomi";
                vi = "bisnis";
            }
            else if (kategori == Kategori.Olahraga)
            {
                dt = "590260";
                an = "olahraga";
                vi = "sport";
                
            }
            else if (kategori == Kategori.Teknologi)
            {
                dt = "590267";
                an = "teknologi";
                vi = "teknologi";
            }

            readerDetik = XmlReader.Create("http://detik.feedsportal.com/c/33613/f/" + dt + "/index.rss");
            //readerKompas = XmlReader.Create("http://www.kompas.com/getrss/sains");
            readerAntara = XmlReader.Create("http://www.antaranews.com/rss/" + an);
            readerViva = XmlReader.Create("http://rss.vivanews.com/get/" + vi);

            feedDetik = SyndicationFeed.Load(readerDetik);
            //feedKompas = SyndicationFeed.Load(readerKompas);
            feedAntara = SyndicationFeed.Load(readerAntara);
            feedViva = SyndicationFeed.Load(readerViva);


            
        }

        //METHOD UNTUK SETTING SEMUA DARI AWAL
        public void getTrendingTopics() 
        {
            Cursor.Current = Cursors.WaitCursor;
            label3.Text = kategori.ToString().ToUpper();
            createReader();
            loadTopics();
            Cursor.Current = Cursors.Default;
        }
               

        private void UserControl1_Load(object sender, EventArgs e)
        {

        }

        //BUTTON UNTUK GET TOPICS, SAMA FUNGSINYA DENGAN REFRESH
        private void button1_Click(object sender, EventArgs e)
        {
            getTrendingTopics();
        }

        //MEMBUAT TRENDING TOPICS
        private void loadTopics()
        {
            listBox1.Items.Clear();

            Dictionary<int, string> trendingTopic = new Dictionary<int, string>();
            Dictionary<string, int> dataKata = new Dictionary<string, int>();

            hitungTopic(feedDetik, dataKata);
            hitungTopic(feedAntara, dataKata);
            hitungTopic(feedViva, dataKata);

            if (kategori == Kategori.Nasional) hitungTopic(feedKompas, dataKata);

            addTopic(dataKata, trendingTopic);

            int x = 1;

            foreach (KeyValuePair<int, string> pair in trendingTopic)
            {
                if (x == 1) keyword = pair.Value;
                listBox1.Items.Add(x + ". " + pair.Value );//+ " (" + dataKata[pair.Value] + ")");
                x++;
            }
            
            Controls.Add(listBox1);
                   
        }

        //MENGAMBIL KATA SEKALIGUS MENGHITUNG FREKUENSI KATA TERSEBUT
        private void hitungTopic(SyndicationFeed feed, Dictionary<string, int> dataKata)
        {
            string tampung;
            string[] wordrct = { "diperiksa", "itu", "dengan", "kalah", "akan", "kalahkan", "posisi", "bikin", "bisa", "tahun", "orang", "tercepat", "awas", "palsu", "terbalik", "utang", "asing", "diduga", "kembali", "hadapi", "lokal", "baru", "jadi", "ingin", "lawan", "id", "kisah", "kenalkan", "kasus", "dia", "terduga", "siap", "triliun", "rp", "ini", "yang", "di", "ke", "dari", "untuk", "pada", "menuju", "masuk", "belum", "sudah", "ada", "si", "dan", "ah", "tapi", "tak", "ada" };

            foreach (SyndicationItem item in feed.Items)
            {
                tampung = string.Format(item.Title.Text);

                var tampgenap = new StringBuilder();
                var tampganjil = new StringBuilder();

                int count = 0;

                foreach (char word in tampung)
                {
                    if (!char.IsPunctuation(word))
                    {
                        if (word == ' ' && count % 2 == 0)
                        {
                            tampgenap.Append('-');
                            tampganjil.Append(' ');
                            count++;
                        }
                        else if (word == ' ' && count % 2 == 1)
                        {
                            tampganjil.Append('-');
                            tampgenap.Append(' ');
                            count++;
                        }
                        else
                        {
                            tampgenap.Append(word);
                            tampganjil.Append(word);
                        }
                    }
                }

                string genap = tampgenap.ToString();
                string ganjil = tampganjil.ToString();

                string[] wordsgenap = genap.Split('-');
                string[] wordsganjil = ganjil.Split('-');

                foreach (string word in wordsganjil)
                {
                    Boolean penting = true;

                    foreach (string rct in wordrct)
                    {
                        if (word.ToLower().IndexOf(rct) != -1)
                        {
                            penting = false;
                            break;
                        }
                    }

                    if (word != "")
                    {
                        Boolean ketemu = false;

                        foreach (KeyValuePair<string, int> pair in dataKata)
                        {
                            if (pair.Key == word)
                            {
                                if (penting)
                                {
                                    dataKata[word] += 2;
                                    ketemu = true;
                                    break;
                                }
                            }
                        }

                        if (!ketemu && word.IndexOf(' ') != -1 && penting)
                        {
                            dataKata.Add(word, 1);
                        }
                    }
                }

                foreach (string word in wordsgenap)
                {
                    Boolean penting = true;

                    foreach (string rct in wordrct)
                    {
                        if (word.ToLower().IndexOf(rct) != -1)
                        {
                            penting = false;
                            break;
                        }
                    }

                    if (word != "")
                    {
                        Boolean ketemu = false;

                        foreach (KeyValuePair<string, int> pair in dataKata)
                        {
                            if (pair.Key == word)
                            {
                                if (penting)
                                {
                                    dataKata[word] += 2;
                                    ketemu = true;
                                    break;
                                }
                            }
                        }
                        if (!ketemu && word.IndexOf(' ') != -1 && penting)
                        {
                            dataKata.Add(word, 1);
                        }
                    }
                }

                foreach (string word in wordsganjil)
                {
                    if (word != "")
                    {
                        foreach (KeyValuePair<string, int> pair in dataKata.ToList())
                        {
                            if (pair.Key == word)
                            {
                                
                            }
                            else if (pair.Key.IndexOf(word) > -1)
                            {
                                dataKata[pair.Key] += 1;
                            }
                        }
                    }
                }

                foreach (string word in wordsgenap)
                {
                    if (word != "")
                    {
                        foreach (KeyValuePair<string, int> pair in dataKata.ToList())
                        {
                            if (pair.Key == word)
                            {
                                
                            }
                            else if (pair.Key.IndexOf(word) > -1)
                            {
                                dataKata[pair.Key] += 1;
                            }
                        }
                    }
                }

                //foreach ( SyndicationLink link in feed.Links)
                //{
                //    MessageBox.Show(link.Uri.ToString());
                //}

            }
        }

        //MENYIMPAN HASIL 5 ATAU 10 TOPICS TERATAS
        private void addTopic(Dictionary<string, int> dataKata, Dictionary<int, string> trendingTopic)
        {
            var items = from pair in dataKata
                        orderby pair.Value descending
                        select pair;

            int count = 0;
            int max;

            if (jumlahTopics == JumlahTopics._5)
            {
                max = 5;
            }
            else
            {
                max = 10;
            }

            foreach (KeyValuePair<string, int> pair in items)
            {
                trendingTopic.Add(count, pair.Key);
                count++;
                if (count == max)
                    break;
            }
        }

        //MEMBUAT ITEMS PADA LISTBOX1 YANG BACKCOLORNYA DISELANG-SELING
        private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
        {
            e.DrawBackground();

            Graphics g = e.Graphics;
            if (e.Index % 2 == 0)
            {
                g.FillRectangle(new SolidBrush(backColorOdd), e.Bounds);
            }
            else
            {
                g.FillRectangle(new SolidBrush(backColorEven), e.Bounds);
            }
            ListBox lb = (ListBox)sender;
            g.DrawString(lb.Items[e.Index].ToString(), e.Font, new SolidBrush(foreColorTopics), new PointF(e.Bounds.X, e.Bounds.Y));

            e.DrawFocusRectangle();
        }


        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void listBox1_Enter(object sender, EventArgs e)
        {
            
        }

        private void listBox1_Leave(object sender, EventArgs e)
        {
           
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            //if (sender.Equals(keyword))
                //MessageBox.Show(e.ToString() + " ||  " + sender.ToString());
        }

        public Dictionary<string, string> getNewsFrom1stTopTopic()
        {
            Dictionary<string, string> dataNews = new Dictionary<string, string>();

            string[] keywordpisah = keyword.Split(' ');
            foreach (string item in keywordpisah)
            {
                getNewsElement(feedViva, dataNews, item);
                getNewsElement(feedAntara, dataNews, item);
                getNewsElement(feedDetik, dataNews, item);
                if (kategori == Kategori.Nasional)
                {
                    getNewsElement(feedKompas, dataNews, item);
                }
                
            }
             
            

            return dataNews;
        }

        private void getNewsElement(SyndicationFeed feed, Dictionary<string, string> data, string keyword)
        {
            string tampung;
            string[] wordrct = { "diperiksa", "itu", "dengan", "kalah", "akan", "kalahkan", "posisi", "bikin", "bisa", "tahun", "orang", "tercepat", "awas", "palsu", "terbalik", "utang", "asing", "diduga", "kembali", "hadapi", "lokal", "baru", "jadi", "ingin", "lawan", "id", "kisah", "kenalkan", "kasus", "dia", "terduga", "siap", "triliun", "rp", "ini", "yang", "di", "ke", "dari", "untuk", "pada", "menuju", "masuk", "belum", "sudah", "ada", "si", "dan", "ah", "tapi", "tak", "ada" };


            foreach (SyndicationItem item in feed.Items)
            {
                tampung = string.Format(item.Title.Text);

                string[] words = tampung.Split(' ');
                foreach (string word in words)
                {
                    string wordtamp = word;

                    var sb = new StringBuilder();

                    foreach (char c in wordtamp)
                    {
                        if (!char.IsPunctuation(c) && !char.IsDigit(c))
                            sb.Append(c);
                    }

                    wordtamp = sb.ToString();

                    Boolean penting = true;

                    foreach (string rct in wordrct)
                    {
                        if (wordtamp.ToLower() == rct)
                        {
                            penting = false;
                            break;
                        }
                    }

                    if (wordtamp != "" && penting && wordtamp == keyword)
                    {
                        bool tes = false;
                        foreach (SyndicationLink li in item.Links)
                        {
                            foreach (KeyValuePair<string, string> pair in data)
                            {
                                if (tampung == pair.Key)
                                {
                                    tes = true;
                                }
                            }
                            if (!tes)
                                data.Add(tampung, li.Uri.ToString());
                        }
                    }
                }
            }
        }
        

        

    }
}
